//
//  MqInfoPictureShowMoreViewController.m
//  Meiqi
//
//  Created by 王郑 on 16/1/15.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqInfoPictureShowMoreViewController.h"
#import "iCarousel.h"
#import "MyImageView.h"
#import "MqInfoPictureDetailModel.h"

@interface MqInfoPictureShowMoreViewController ()<iCarouselDataSource,iCarouselDelegate>


// 展示到第几张图片的
@property (strong, nonatomic) UILabel *pageLabel;
@property (strong, nonatomic) UILabel *contentLabel;

// 展样式按钮
@property (strong, nonatomic) UIButton *showStyleButton;
// 保存图片的按钮
@property (strong, nonatomic) UIButton *saveButton;


// 毛玻璃效果
@property (strong, nonatomic) MyImageView *imageV;

@property (strong, nonatomic) UIImageView *showImageV;

@property (assign, nonatomic) NSInteger tag;

@property (strong, nonatomic) iCarousel *icarousel;

@end

@implementation MqInfoPictureShowMoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];

 
    
    
    UIView *funView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64*kHeightBase, kScreenWidth, 64*kHeightBase)];
    funView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:funView];
    
    
    //当前页
    _pageLabel = [[UILabel alloc] initWithFrame:CGRectMake((kScreenWidth - 100*kWidthBase)/2,0,100*kWidthBase,40 *kHeightBase)];
    _pageLabel.textAlignment = NSTextAlignmentCenter;
    _pageLabel.text = [NSString stringWithFormat:@"%ld / %ld",(long)_indexStart + 1,(unsigned long)_imagesArray.count];
    _pageLabel.textColor = [UIColor whiteColor];
    [funView addSubview:_pageLabel];
    
    _contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(40*kWidthBase, _pageLabel.bottom, kScreenWidth - 80*kWidthBase, funView.height - _pageLabel.bottom)];
     _contentLabel.textAlignment = NSTextAlignmentCenter;
    [funView addSubview:_contentLabel];

    
    // 毛玻璃:
    MqInfoPictureDetailModel *model = _imagesArray[_indexStart];
    _imageV = [[MyImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64*kHeightBase)];
    _imageV.userInteractionEnabled = YES;
    // 毛玻璃展示的初始图片
    [_imageV sd_setImageWithURL:[NSURL URLWithString:model.titlePic] placeholderImage:[UIImage imageNamed:@"infoplaceholder"]];
    _contentLabel.text = model.title;
    [self.view addSubview:_imageV];

    
    
    
    // 样式按钮
    _showStyleButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _showStyleButton.frame = CGRectMake(kScreenWidth - 30*kWidthBase, kScreenHeight - 94*kHeightBase, 30*kWidthBase, 30*kHeightBase);
    [_showStyleButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [_showStyleButton setTitle:@"magic" forState:(UIControlStateNormal)];
    [_showStyleButton setBackgroundImage:[UIImage imageNamed:@"info-magicwand"] forState:(UIControlStateNormal)];
    [self.view addSubview:_showStyleButton];
    [_showStyleButton addTarget:self action:@selector(showPicture:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [self addCarousl];
    

    
    // 保存按钮
    _saveButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _saveButton.frame = CGRectMake(_showStyleButton.left, kScreenHeight - 30*kHeightBase, 30*kWidthBase, 30*kHeightBase);
    [_saveButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [self.view addSubview:_saveButton];
    [_saveButton setBackgroundImage:[UIImage imageNamed:@"info-save"] forState:(UIControlStateNormal)];
    [_saveButton addTarget:self action:@selector(savePicture:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

- (void)addCarousl
{
  
    _icarousel = [[iCarousel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _icarousel.dataSource = self;
    _icarousel.delegate = self;
    _icarousel.type = _type;
    
    _icarousel.pagingEnabled = YES;
    _icarousel.scrollOffset = _indexStart;
    [self.view addSubview:_icarousel];
    
    //轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 2;
    [_icarousel addGestureRecognizer:tap];

    
    [self.view bringSubviewToFront:_showStyleButton];
    [self.view bringSubviewToFront:_saveButton];
    
}

- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    
    return _imagesArray.count;
    
}


// 返回每个item对应的ImageView;
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(nullable UIView *)view
{
 
    MqInfoPictureDetailModel *model = _imagesArray[index];
    _showImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 200, 200)];
    [_showImageV sd_setImageWithURL:[NSURL URLWithString:model.titlePic] placeholderImage:[UIImage imageNamed:@"infoplaceholder"]];
    
    return _showImageV;
}

-(void)carouselDidEndScrollingAnimation:(iCarousel * __nonnull)carousel
{
    // 该变毛玻璃图片
    NSInteger index = carousel.scrollOffset;
    MqInfoPictureDetailModel *model = _imagesArray[index];
   [_imageV sd_setImageWithURL:[NSURL URLWithString:model.titlePic] placeholderImage:[UIImage imageNamed:@"infoplaceholder"]];
   _pageLabel.text = [NSString stringWithFormat:@"%ld / %ld",
                      index + 1,(unsigned long)_imagesArray.count];

    _contentLabel.text = model.title;
}





- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}



#pragma mark ----- 打开本地的相册,保存起来
//
//- (void)savePicture:(UIButton *)button
//{
//    
//    
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        
//        
//        BOOL isAllowToSave = NO;
//        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//        [userDefault setBool:isAllowToSave forKey:@"是否允许"];
//        [userDefault synchronize];
//        
//        
//        
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"破风想要访问您的照片" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
//        
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//
//            // 设置为允许保存
//            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//            BOOL isAllowToSave = [userDefault valueForKey:@"是否允许"];
//            isAllowToSave = YES;
//            [userDefault setBool:isAllowToSave forKey:@"是否允许"];
//            [userDefault synchronize];
//            
//            // 保存操作
//            UIImageView *imageV = (UIImageView *)_icarousel.currentItemView;
//            UIImage *saveImage = imageV.image;
//            UIImageWriteToSavedPhotosAlbum(saveImage,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
//
//        }];
//        
//        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"不允许" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
//            
//            // 设置为不允许保存
//            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//            BOOL isAllowToSave = [userDefault valueForKey:@"是否允许"];
//            isAllowToSave = NO;
//            [userDefault setBool:isAllowToSave forKey:@"是否允许"];
//            [userDefault synchronize];
//            
//        }];
//        
//        [alert addAction:action];
//        [alert addAction:action2];
//        // 模态展示出消息框
//        [self presentViewController:alert animated:YES completion:nil];
//
//    });
//    
//    
//    
//    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//    BOOL isAllowToSave = [userDefault valueForKey:@"是否允许"];
//    NSLog(@"啦啦啦%d",isAllowToSave);
//    // 保存照片到系统相册（PhotoAlbum）
//    if (isAllowToSave == 1) {
//        
//        UIImageView *imageV = (UIImageView *)_icarousel.currentItemView;
//        UIImage *saveImage = imageV.image;
//        UIImageWriteToSavedPhotosAlbum(saveImage,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
//        
//    } else
//    {
//        return;
//    }
//    
//   
//}


- (void)savePicture:(UIButton *)button
{
    UIImageView *imageV = (UIImageView *)_icarousel.currentItemView;
    UIImage *saveImage = imageV.image;
    
    UIImageWriteToSavedPhotosAlbum(saveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    
}


// 3秒后消息框自动消失
- (void)dismissAlert:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
}


//指定回调方法
-(void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo

{
    
    if(!error){
        
       
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"保存成功" preferredStyle:(UIAlertControllerStyleAlert)];
        // 模态展示出消息框
        [self presentViewController:alert animated:YES completion:nil];
        // 3秒后自动消失
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:2];

        
    
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"保存失败" preferredStyle:(UIAlertControllerStyleAlert)];
        // 模态展示出消息框
        [self presentViewController:alert animated:YES completion:nil];
        // 3秒后自动消失
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:2];
        
    }
    
}


- (void)showPicture:(UIButton *)button
{
    [_icarousel removeFromSuperview];
    _type = arc4random()%11;
    
    // 改变状态前保存当前所处的位置
    NSInteger index = _icarousel.scrollOffset;
    _indexStart = index;
    // 重新添加ica;
    [self addCarousl];

    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
